// 云函数入口文件
const cloud = require('wx-server-sdk')

// 初始化 cloud
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  console.log('voteManager云函数接收到的事件:', event)
  
  const wxContext = cloud.getWXContext()
  const { OPENID } = wxContext
  
  try {
    const { action } = event
    
    switch (action) {
      case 'vote':
        return await handleVote(event, OPENID)
      case 'getVoteRecords':
        return await getVoteRecords(event, OPENID)
      case 'getVoteStatus':
        return await getVoteStatus(event, OPENID)
      case 'getActivityVoteStats':
        return await getActivityVoteStats(event, OPENID)
      default:
        return {
          success: false,
          message: '未知操作类型'
        }
    }
  } catch (error) {
    console.error('voteManager云函数执行失败:', error)
    return {
      success: false,
      message: '操作失败，请重试',
      error: error.message
    }
  }
}

// 处理投票
async function handleVote(event, openId) {
  const { activityId, candidateIds } = event
  
  console.log('=== handleVote 调试信息 ===')
  console.log('接收到的事件:', event)
  console.log('OpenID:', openId)
  console.log('活动ID:', activityId)
  console.log('候选人IDs:', candidateIds)
  
  // 验证参数
  if (!activityId) {
    console.log('错误：活动ID为空')
    return {
      success: false,
      message: '活动ID不能为空'
    }
  }
  
  if (!candidateIds || !Array.isArray(candidateIds) || candidateIds.length === 0) {
    console.log('错误：候选人ID无效')
    return {
      success: false,
      message: '请选择投票对象'
    }
  }
  
  if (!openId) {
    console.log('错误：OpenID为空')
    return {
      success: false,
      message: '请先登录'
    }
  }
  
  try {
    // 1. 验证用户是否已登录和存在
    console.log('步骤1：查找用户...')
    const userResult = await db.collection('users').where({
      openId: openId
    }).get()
    
    console.log('用户查询结果:', userResult)
    
    if (userResult.data.length === 0) {
      console.log('错误：用户不存在')
      return {
        success: false,
        message: '用户不存在，请重新登录'
      }
    }
    
    const user = userResult.data[0]
    console.log('找到用户:', user)
    
    // 2. 检查活动是否存在和有效
    console.log('步骤2：查找活动...')
    const activityResult = await db.collection('activities').doc(activityId).get()
    
    console.log('活动查询结果:', activityResult)
    
    if (!activityResult.data) {
      console.log('错误：活动不存在')
      return {
        success: false,
        message: '投票活动不存在'
      }
    }
    
    const activity = activityResult.data
    const currentTime = new Date()
    console.log('找到活动:', activity)
    
    // 验证活动状态
    if (activity.status !== 'ongoing') {
      console.log('错误：活动状态不是ongoing，当前状态:', activity.status)
      return {
        success: false,
        message: '投票活动未开始或已结束'
      }
    }
    
    // 验证投票时间
    if (activity.startTime && currentTime < new Date(activity.startTime)) {
      console.log('错误：投票尚未开始')
      return {
        success: false,
        message: '投票尚未开始'
      }
    }
    
    if (activity.endTime && currentTime > new Date(activity.endTime)) {
      console.log('错误：投票已结束')
      return {
        success: false,
        message: '投票已结束'
      }
    }
    
    // 3. 检查用户的投票记录（修改逻辑：检查具体投票情况）
    console.log('步骤3：检查用户投票记录...')
    const existingVoteRecords = await db.collection('vote_records').where({
      activityId: activityId,
      userId: user._id
    }).get()
    
    console.log('用户投票记录查询结果:', existingVoteRecords)
    
    // 计算用户已投票的候选人和总投票数
    const votedCandidateIds = []
    let totalVotedCount = 0
    
    existingVoteRecords.data.forEach(record => {
      if (record.candidateIds && Array.isArray(record.candidateIds)) {
        votedCandidateIds.push(...record.candidateIds)
        totalVotedCount += record.candidateIds.length
      }
    })
    
    console.log('用户已投票的候选人:', votedCandidateIds)
    console.log('用户总投票数:', totalVotedCount)
    console.log('活动投票限制:', activity.voteLimit)
    
    // 检查是否给同一个候选人重复投票
    const duplicateCandidates = candidateIds.filter(id => votedCandidateIds.includes(id))
    if (duplicateCandidates.length > 0) {
      console.log('错误：重复投票给相同候选人:', duplicateCandidates)
      return {
        success: false,
        message: '您已经为该候选人投过票了'
      }
    }
    
    // 检查投票总数是否超过限制
    const newTotalVotes = totalVotedCount + candidateIds.length
    if (newTotalVotes > activity.voteLimit) {
      console.log('错误：超过投票总数限制')
      const remainingVotes = activity.voteLimit - totalVotedCount
      return {
        success: false,
        message: `您已投票${totalVotedCount}次，最多还能投票${remainingVotes}次`
      }
    }
    
    // 4. 验证本次投票数量
    console.log('步骤4：验证本次投票数量...')
    if (candidateIds.length > 1) {
      console.log('错误：本次投票数量过多')
      return {
        success: false,
        message: '每次只能为一个候选人投票'
      }
    }
    
    // 5. 验证候选人是否存在且属于该活动
    console.log('步骤5：验证候选人...')
    const candidatesResult = await db.collection('candidates').where({
      _id: _.in(candidateIds),
      activityId: activityId,
      status: 'active'
    }).get()
    
    console.log('候选人查询结果:', candidatesResult)
    
    if (candidatesResult.data.length !== candidateIds.length) {
      console.log('错误：候选人验证失败')
      return {
        success: false,
        message: '选择的候选人无效'
      }
    }
    
    // 6. 开始事务操作
    console.log('步骤6：开始事务操作...')
    const transaction = await db.startTransaction()
    
    try {
      // 创建投票记录
      const voteRecord = {
        activityId: activityId,
        userId: user._id,
        userOpenId: openId,
        userName: user.nickName || '匿名用户',
        candidateIds: candidateIds,
        voteTime: currentTime,
        createTime: currentTime
      }
      
      console.log('创建投票记录:', voteRecord)
      
      await transaction.collection('vote_records').add({
        data: voteRecord
      })
      
      // 更新候选人票数
      for (const candidateId of candidateIds) {
        console.log('更新候选人票数:', candidateId)
        await transaction.collection('candidates').doc(candidateId).update({
          data: {
            votes: _.inc(1),
            updateTime: currentTime
          }
        })
      }
      
      // 更新活动统计
      const isFirstTimeVoter = existingVoteRecords.data.length === 0
      const updateData = {
        totalVotes: _.inc(candidateIds.length),
        updateTime: currentTime
      }
      
      if (isFirstTimeVoter) {
        updateData.participantCount = _.inc(1)
      }
      
      console.log('更新活动统计:', updateData)
      
      await transaction.collection('activities').doc(activityId).update({
        data: updateData
      })
      
      // 提交事务
      console.log('提交事务...')
      await transaction.commit()
      
      console.log('投票成功！')
      return {
        success: true,
        message: '投票成功',
        data: {
          voteTime: currentTime,
          voteCount: candidateIds.length,
          totalVoted: newTotalVotes,
          remainingVotes: activity.voteLimit - newTotalVotes
        }
      }
      
    } catch (transactionError) {
      // 回滚事务
      console.error('事务错误，回滚:', transactionError)
      await transaction.rollback()
      throw transactionError
    }
    
  } catch (error) {
    console.error('投票失败:', error)
    return {
      success: false,
      message: '投票失败，请重试',
      error: error.message
    }
  }
}

// 获取用户投票记录
async function getVoteRecords(event, openId) {
  if (!openId) {
    return {
      success: false,
      message: '请先登录'
    }
  }
  
  try {
    // 获取用户信息
    const userResult = await db.collection('users').where({
      openId: openId
    }).get()
    
    if (userResult.data.length === 0) {
      return {
        success: false,
        message: '用户不存在'
      }
    }
    
    const user = userResult.data[0]
    
    // 获取投票记录，关联活动信息
    const voteRecordsResult = await db.collection('vote_records')
      .aggregate()
      .match({
        userId: user._id
      })
      .lookup({
        from: 'activities',
        localField: 'activityId',
        foreignField: '_id',
        as: 'activity'
      })
      .unwind('$activity')
      .lookup({
        from: 'candidates',
        localField: 'candidateIds',
        foreignField: '_id',
        as: 'candidates'
      })
      .sort({
        voteTime: -1
      })
      .end()
    
    const voteRecords = voteRecordsResult.list.map(record => ({
      id: record._id,
      activityId: record.activityId,
      activityTitle: record.activity.title,
      activityCover: record.activity.coverUrl,
      voteTime: formatDate(record.voteTime),
      voteCount: record.candidateIds.length,
      candidates: record.candidates.map(candidate => ({
        id: candidate._id,
        name: candidate.name,
        imageUrl: candidate.images && candidate.images[0] ? candidate.images[0] : null
      }))
    }))
    
    return {
      success: true,
      data: {
        voteRecords
      }
    }
    
  } catch (error) {
    console.error('获取投票记录失败:', error)
    return {
      success: false,
      message: '获取投票记录失败',
      error: error.message
    }
  }
}

// 获取用户在特定活动的投票状态
async function getVoteStatus(event, openId) {
  const { activityId, candidateId } = event
  
  if (!activityId) {
    return {
      success: false,
      message: '活动ID不能为空'
    }
  }
  
  if (!openId) {
    return {
      success: true,
      data: {
        hasVotedForCandidate: false,
        totalVoted: 0,
        remainingVotes: 0,
        voteRecords: []
      }
    }
  }
  
  try {
    // 获取活动信息
    const activityResult = await db.collection('activities').doc(activityId).get()
    if (!activityResult.data) {
      return {
        success: false,
        message: '活动不存在'
      }
    }
    
    const activity = activityResult.data
    
    // 获取用户信息
    const userResult = await db.collection('users').where({
      openId: openId
    }).get()
    
    if (userResult.data.length === 0) {
      return {
        success: true,
        data: {
          hasVotedForCandidate: false,
          totalVoted: 0,
          remainingVotes: activity.voteLimit || 1,
          voteRecords: []
        }
      }
    }
    
    const user = userResult.data[0]
    
    // 检查投票记录
    const voteResult = await db.collection('vote_records').where({
      activityId: activityId,
      userId: user._id
    }).get()
    
    // 计算投票统计
    const votedCandidateIds = []
    let totalVoted = 0
    const voteRecords = []
    
    voteResult.data.forEach(record => {
      if (record.candidateIds && Array.isArray(record.candidateIds)) {
        votedCandidateIds.push(...record.candidateIds)
        totalVoted += record.candidateIds.length
        
        voteRecords.push({
          voteTime: formatDate(record.voteTime),
          candidateIds: record.candidateIds
        })
      }
    })
    
    // 检查是否给特定候选人投过票
    const hasVotedForCandidate = candidateId ? votedCandidateIds.includes(candidateId) : false
    
    // 计算剩余投票数
    const voteLimit = activity.voteLimit || 1
    const remainingVotes = Math.max(0, voteLimit - totalVoted)
    
    if (voteResult.data.length > 0) {
      // 获取投票的候选人信息
      const candidatesResult = await db.collection('candidates').where({
        _id: _.in(votedCandidateIds)
      }).get()
      
      return {
        success: true,
        data: {
          hasVotedForCandidate: hasVotedForCandidate,
          totalVoted: totalVoted,
          voteLimit: voteLimit,
          remainingVotes: remainingVotes,
          canVoteMore: remainingVotes > 0,
          votedCandidateIds: votedCandidateIds,
          voteRecords: voteRecords,
          candidates: candidatesResult.data.map(candidate => ({
            id: candidate._id,
            name: candidate.name,
            imageUrl: candidate.images && candidate.images[0] ? candidate.images[0] : null
          }))
        }
      }
    } else {
      return {
        success: true,
        data: {
          hasVotedForCandidate: false,
          totalVoted: 0,
          voteLimit: voteLimit,
          remainingVotes: voteLimit,
          canVoteMore: true,
          votedCandidateIds: [],
          voteRecords: [],
          candidates: []
        }
      }
    }
    
  } catch (error) {
    console.error('获取投票状态失败:', error)
    return {
      success: false,
      message: '获取投票状态失败',
      error: error.message
    }
  }
}

// 获取活动投票统计
async function getActivityVoteStats(event, openId) {
  const { activityId } = event
  
  if (!activityId) {
    return {
      success: false,
      message: '活动ID不能为空'
    }
  }
  
  try {
    // 获取活动基本信息
    const activityResult = await db.collection('activities').doc(activityId).get()
    
    if (!activityResult.data) {
      return {
        success: false,
        message: '活动不存在'
      }
    }
    
    // 获取候选人排名（按票数排序）
    const candidatesResult = await db.collection('candidates')
      .where({
        activityId: activityId,
        status: 'active'
      })
      .orderBy('votes', 'desc')
      .orderBy('createTime', 'asc')
      .get()
    
    // 获取总投票人数
    const voteRecordsResult = await db.collection('vote_records')
      .where({
        activityId: activityId
      })
      .count()
    
    return {
      success: true,
      data: {
        activity: activityResult.data,
        candidates: candidatesResult.data,
        participantCount: voteRecordsResult.total,
        totalVotes: candidatesResult.data.reduce((sum, candidate) => sum + candidate.votes, 0)
      }
    }
    
  } catch (error) {
    console.error('获取活动统计失败:', error)
    return {
      success: false,
      message: '获取活动统计失败',
      error: error.message
    }
  }
}

// 格式化日期
function formatDate(date) {
  if (!date) return ''
  
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hour = String(d.getHours()).padStart(2, '0')
  const minute = String(d.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hour}:${minute}`
} 